package com.faneui.transfer.gateway.exception;

import com.faneui.transfer.gateway.model.OutputBean;
import com.faneui.transfer.gateway.utils.BeanAssemblyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice(annotations = RestController.class)
public class ApiExceptionHandlerAdvice {

	private static final Logger logger = LoggerFactory.getLogger(ApiExceptionHandlerAdvice.class);

	@ExceptionHandler(value = WmsException.class)
	@ResponseBody
	public OutputBean exception(WmsException exception, WebRequest request) {
		return BeanAssemblyUtils.ERROR(exception);
	}

	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	@ResponseBody
	public OutputBean handleMethodArgumentNotValidException(MethodArgumentNotValidException exception,
			WebRequest request) {
		BindingResult bindingResult = exception.getBindingResult();

		String errorMesssage = "";

		for (FieldError fieldError : bindingResult.getFieldErrors()) {
			errorMesssage += fieldError.getDefaultMessage() + "\n";
		}
		return BeanAssemblyUtils
				.ERROR(new WmsException(WmsExceptionEnum.PARAM_ILLEGAL.getCode(), errorMesssage));
	}

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public OutputBean exception(Exception exception, WebRequest request) {
		logger.error(exception.getMessage(), exception);
		return BeanAssemblyUtils.ERROR(new WmsException(WmsExceptionEnum.SYSTEM_ERROR.getCode(),
                exception.getMessage()));
	}
}
